package com.library.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.bean.Book;
import com.library.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;



@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bs;

    @GetMapping("/getBooks")
    @ResponseBody
    public Object getBooks(Book book,
                           @RequestParam(required = false, defaultValue = "1") int pageNum,
                           @RequestParam(required = false, defaultValue = "10") int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        Page<Book> page = (Page<Book>) bs.getBooks(book);
        return page.toPageInfo();
    }

    @PostMapping("/addBook")
    public String addBook(Book book, Model model) {
        bs.addBook(book);
        return "redirect:/books";
    }

    @RequestMapping("/deleteBook")
    @ResponseBody
    public String deleteBook(int bookId) {
        int result = bs.deleteBook(bookId);
        return result == 1 ? "success" : "fail";
    }

    @RequestMapping("/update")
    public String updatePage(int bookId, Model model) {
        Book book = bs.getBookById(bookId);
        model.addAttribute("book", book);
        return "forward:/WEB-INF/update.jsp";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Book book, MultipartFile mf) {
        bs.updateBook(book);
        return "redirect:/books";
    }
}